<template>
	<view class="emoji-container">
		<view class="header">
			<text class="title">表情包搜索</text>
			<text class="subtitle">输入关键词，获取图片和视频</text>
		</view>

		<view class="search-bar">
			<input v-model="keyword" class="search-input" placeholder="例如：龙图、狗头、猫猫..." @confirm="doSearch" />
			<button class="btn" :disabled="!keyword || loading" @click="doSearch">{{ loading ? '搜索中...' : '搜索' }}</button>
		</view>

		<view v-if="errorMsg" class="error">{{ errorMsg }}</view>

		<scroll-view scroll-y class="result">
			<view v-if="items.length === 0 && !loading" class="empty">尚无结果，试试其他关键词</view>
			<view class="grid">
				<view v-for="(it, idx) in items" :key="idx" class="card" @click="preview(it)">
					<image v-if="it.thumbSrc" :src="normalizeUrl(it.thumbSrc)" class="thumb" mode="aspectFill" />
					<view v-else class="thumb thumb-missing">No Image</view>
					<view class="meta">
						<text class="idx">#{{ idx + 1 }}</text>
						<text class="type" v-if="it.source" @click.stop="openSourceFromCard(it, $event)">来源</text>
						<text class="type" v-else>图片</text>
					</view>
				</view>
			</view>
		</scroll-view>

		<!-- 预览弹层：视频优先，其次图片 -->
		<view v-if="showPreview" class="preview-mask" @click="closePreview">
			<!-- 优先尝试显示视频 -->
			<video 
				v-if="current?.source && !videoLoadError" 
				:src="normalizeUrl(current.source)" 
				controls 
				preload="metadata"
				class="preview-video" 
				@click.stop="noop"
				@error="onVideoError"
				@loadstart="onVideoLoadStart" />
			
			<!-- 如果是纯图片或者视频加载失败，显示图片 -->
			<image 
				v-if="(!current?.source || videoLoadError) && current?.thumbSrc"
				:src="normalizeUrl(current.thumbSrc)" 
				class="preview-image" 
				mode="contain" 
				@click.stop="noop" />
			
			<!-- 既无视频又无图片的情况 -->
			<view v-if="(!current?.source || videoLoadError) && !current?.thumbSrc" 
				class="preview-placeholder">
				<text>无法预览此内容</text>
			</view>
			
			<!-- 简化来源标签，仅在非H5环境或找不到链接时显示 -->
			<view v-if="current && current.source && (getPlatform() !== 'h5')" 
				class="preview-source" 
				@click.stop="openSource">
				<text class="source-text">打开原链接</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
	data() {
		return {
			keyword: '',
			loading: false,
			items: [],
			errorMsg: '',
			showPreview: false,
			current: null,
			videoLoadError: false  // 添加视频加载错误状态
		}
	},
	methods: {
		normalizeUrl(u) {
			if (!u) return '';
			return String(u).replace(/\\\//g, '/');
		},
		
		// 视频加载开始处理
		onVideoLoadStart(event) {
			console.log('视频开始加载:', event);
			this.videoLoadError = false; // 重置错误状态
		},
		
		// 视频错误处理 - 尝试失败时切换到图片
		onVideoError(event) {
			console.log('视频加载失败，切换到图片预览:', event);
			this.videoLoadError = true;
		},
		
		// 从卡片直接点击来源，跳转到网页
		openSourceFromCard(item, event) {
			event && event.stopPropagation(); // 阻止冒泡到卡片的preview事件
			
			let sourceUrl = item.source;
			
			if (!sourceUrl) {
				console.log('该条目没有来源链接');
				uni.showToast({
					title: '该条目没有来源',
					icon: 'none'
				});
				return;
			}
			
			// 规范化URL
			sourceUrl = this.normalizeUrl(sourceUrl);
			
			console.log('从卡片点击跳转到来源:', sourceUrl);
			
			this.openUrlInBrowser(sourceUrl);
		},
		
		// 统一的链接打开方法
		openUrlInBrowser(url) {
			// 提取域名作为展示文本
			let displayUrl = url;
			try {
				const urlObj = new URL(url);
				displayUrl = urlObj.hostname;
			} catch (e) {
				// URL解析失败，使用原URL
			}
			
			// H5环境：尝试在新标签页打开
			// #ifdef H5
			try {
				const opened = window.open(url, '_blank');
				if (opened) {
					uni.showToast({
						title: '已在浏览器打开',
						icon: 'success'
					});
				} else {
					// 可能被弹窗阻止器阻止，尝试其他方法
					this.copyUrlToClipboard(url);
				}
			} catch (e) {
				console.log('H5浏览器打开失败:', e);
				this.copyUrlToClipboard(url);
			}
			// #endif
			
			// 非H5环境：复制到剪贴板
			// #ifndef H5
			uni.showModal({
				title: '来源链接',
				content: displayUrl + '\n\n将复制到剪贴板',
				showCancel: true,
				cancelText: '取消',
				confirmText: '复制'
			}).then(res => {
				if (res[1].confirm) {
					this.copyUrlToClipboard(url);
				}
			});
			// #endif
		},
		
		// 复制URL到剪贴板
		copyUrlToClipboard(url) {
			uni.setClipboardData({
				data: url,
				success: () => {
					uni.showToast({
						title: '链接已复制到剪贴板',
						icon: 'success'
					});
				},
				fail: () => {
					uni.showModal({
						title: '来源链接',
						content: url
					});
				}
			});
		},
		
		// 获取平台类型
		getPlatform() {
			// #ifdef H5
			return 'h5';
			// #endif
			
			// #ifdef MP-WEIXIN
			return 'mp-weixin';
			// #endif
			
			// #ifdef APP-PLUS
			return 'app';
			// #endif
			
			return 'unknown';
		},
		
		// 点击来源标签，跳转到网页（预览弹窗中的）
		openSource() {
			if (!this.current) {
				console.log('没有当前内容，无法获取来源');
				return;
			}
			
			// 优先使用视频源，其次图片源
			let sourceUrl = this.current.source || this.current.thumbSrc;
			
			if (!sourceUrl) {
				console.log('无法获取内容来源URL');
				uni.showToast({
					title: '无法获取来源链接',
					icon: 'none'
				});
				return;
			}
			
			// 规范化URL
			sourceUrl = this.normalizeUrl(sourceUrl);
			
			this.openUrlInBrowser(sourceUrl);
		},
		async doSearch() {
			if (!this.keyword || this.loading) return;
			this.loading = true;
			this.errorMsg = '';
			try {
				const keyword = encodeURIComponent(this.keyword);
				const originalApi = `https://api.tangdouz.com/a/biaoq.php?return=json&nr=${keyword}`;
				
				let apiUrl, data;
				
				// 分别处理H5和原生环境
				// #ifdef H5
				// 采用allorigins代理服务，自动处理CORS
				apiUrl = `https://api.allorigins.win/raw?url=${encodeURIComponent(originalApi)}`;
				// #endif
				
				// #ifndef H5
				apiUrl = originalApi;
				// #endif
				
				const res = await new Promise((resolve, reject) => {
					uni.request({
						url: apiUrl,
						method: 'GET',
						timeout: 15000,
						sslVerify: false,
						success: (response) => {
							console.log('API响应:', response);
							if (response.statusCode === 200) {
								resolve(response);
							} else {
								reject(new Error(`HTTP ${response.statusCode} - 请稍后重试`));
							}
						},
						fail: (error) => {
							console.error('网络请求失败:', error);
							reject(new Error(`网络连接失败: ${error.errMsg}`));
						}
					});
				});
				
				// 处理返回的数据，支持字符串和对象
				data = res.data;
				
				if (typeof data === 'string' && data.trim()) {
					try {
						data = JSON.parse(data);
					} catch (parseError) {
						console.error('JSON解析失败:', parseError);
						throw new Error('数据格式错误，请检查API服务');
					}
				}
				
				if (!Array.isArray(data)) {
					console.log('返回数据不是数组:', data, typeof data);
					throw new Error('API返回数据格式不正确');
				}
				
				// 处理并过滤数据
				this.items = data
					.map((item, index) => {
						const processedItem = {
							thumbSrc: item.thumbSrc || item.thumb || item.pic || item.image || '',
							source: item.source || item.video || item.url || ''
						};
						
						// 详细调试
						console.log(`原始数据 ${index}:`, {
							原数据: item,
							处理结果: processedItem,
							是否有视频源: !!processedItem.source,
							是否有图片源: !!processedItem.thumbSrc
						});
						
						return processedItem;
					})
					.filter(item => {
						// 保留有图片或视频的条目，并记录过滤原因
						const hasContent = item.thumbSrc || item.source;
						if (!hasContent) {
							console.log('过滤掉无效条目:', item);
						}
						return hasContent;
					});
				
				if (this.items.length === 0) {
					this.errorMsg = '未找到相关表情包，请尝试其他关键词';
				} else {
					this.errorMsg = '';
				}
			} catch (e) {
				console.error('搜索失败:', e);
				this.errorMsg = e.message || '搜索失败，请稍后重试';
			} finally {
				this.loading = false;
			}
		},
		preview(it) {
			this.current = it;
			this.showPreview = true;
			this.videoLoadError = false; // 重置视频错误状态
			
			console.log('预览内容:', {
				source: it.source,
				thumbSrc: it.thumbSrc,
				fullItem: it
			});
			
			// 判断内容类型和URL
			if (it.source) {
				console.log('尝试播放视频:', it.source);
			}
			if (it.thumbSrc) {
				console.log('备用图片:', it.thumbSrc);
			}
		},
		closePreview() {
			this.showPreview = false;
			this.current = null;
			this.videoLoadError = false;
		},
			noop() {}
		}
	}
</script>

<style scoped>
	.emoji-container { min-height: 100vh; background: #f6f7fb; padding: 20rpx; }
	.header { text-align: center; margin-bottom: 20rpx; }
	.title { display:block; font-size: 36rpx; font-weight: bold; color: #333; margin-bottom: 8rpx; }
	.subtitle { display:block; font-size: 24rpx; color: #666; }
	.search-bar { display:flex; gap: 12rpx; margin: 16rpx 0 20rpx; }
	.search-input { flex:1; background:#fff; border-radius: 12rpx; padding: 12rpx 16rpx; font-size: 26rpx; }
	.btn { background:#667eea; color:#fff; border:none; border-radius: 10rpx; padding: 12rpx 20rpx; font-size: 24rpx; font-weight: bold; }
	.error { color:#e53935; font-size: 22rpx; margin-bottom: 12rpx; text-align:center; }
	.result { height: calc(100vh - 240rpx); }
	.grid { display:grid; grid-template-columns: repeat(2, 1fr); gap: 16rpx; }
	.card { background:#fff; border-radius: 12rpx; overflow:hidden; box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.08); }
	.thumb { width: 100%; height: 280rpx; background:#f2f2f2; }
	.thumb-missing { width:100%; height:280rpx; display:flex; align-items:center; justify-content:center; color:#999; }
	.meta { display:flex; align-items:center; justify-content:space-between; padding: 10rpx 12rpx; }
	.idx { font-size: 22rpx; color:#666; }
	.type { 
		font-size: 22rpx; 
		color:#667eea; 
		padding: 4rpx 8rpx;
		border-radius: 8rpx;
		transition: all 0.2s ease;
	}
	.type:hover { 
		background: rgba(102, 126, 234, 0.1); 
		transform: scale(1.05);
	}
	.meta { 
		display:flex; 
		align-items:center; 
		justify-content:space-between; 
		padding: 10rpx 12rpx;
		cursor: pointer;
	}
	.empty { text-align:center; color:#999; padding: 40rpx 0; }
	.preview-mask { 
		position:fixed; 
		left:0; 
		top:0; 
		right:0; 
		bottom:0; 
		background: rgba(0,0,0,0.8); 
		display:flex; 
		align-items:center; 
		justify-content:center; 
		z-index: 1000; 
	}
	.preview-video { 
		width: 90vw; 
		height: 50vh; 
		background:#000; 
		border-radius: 8px;
	}
	.preview-image { 
		width: 90vw; 
		height: 70vh;
		border-radius: 8px;
	}
	.preview-placeholder {
		width: 90vw;
		height: 50vh;
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgba(255,255,255,0.1);
		border-radius: 8px;
		border: 2px dashed rgba(255,255,255,0.3);
	}
	.preview-placeholder text {
		color: rgba(255,255,255,0.7);
		font-size: 32rpx;
	}
	
	/* 来源标签样式 */
	.preview-source {
		position: absolute;
		bottom: 20rpx;
		right: 20rpx;
		background: rgba(0, 0, 0, 0.7);
		color: #fff;
		padding: 12rpx 18rpx;
		border-radius: 24rpx;
		display: flex;
		align-items: center;
		gap: 8rpx;
		font-size: 24rpx;
		cursor: pointer;
		transition: all 0.2s ease;
		backdrop-filter: blur(8px);
	}
	
	.preview-source:hover {
		background: rgba(0, 0, 0, 0.8);
		transform: translateY(-2px);
	}
	
	.preview-source:active {
		transform: translateY(0);
		background: rgba(0, 0, 0, 0.9);
	}
	
	.source-text {
		font-size: 24rpx;
		color: #fff;
	}
	
	.source-icon {
		font-size: 28rpx;
		color: #4CAF50;
		font-weight: bold;
	}
</style> 